package chapter3;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ycj
 * @version 1.0
 * @description: TODO
 * @date 2022/5/17
 */
public class Source3_2 {
    public static void main(String[] args) {
        Thread[] threads=new Thread[20];
        Work work = new Work();
        for(int i=0;i<20;i++){
            threads[i]=new Thread(work);
        }

        for (Thread thread : threads) {
            thread.start();
        }
    }

}

class Work implements Runnable{
    private static int data=0;
    //显示的可重入锁
    private static final ReentrantLock lock=new ReentrantLock();

    @Override
    public void run() {
        lock.lock();//获取锁
        try {
            data++;
            System.out.println(data);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();//释放锁的操作必须放到finally
        }
    }
}


